package pers.wz.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import pers.wz.handler.NettyChatClientHandler;

import java.util.Scanner;

public class NettyChatClient2 {
    private String ip;//服务端IP
    private int port;//服务端端口号
    public NettyChatClient2(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyChatClient2("127.0.0.1",9998).run();
    }

    public void run() throws InterruptedException {
        EventLoopGroup group = null;

        try {
            group = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new StringEncoder());
                            socketChannel.pipeline().addLast(new NettyChatClientHandler());

                        }
                    });
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            future.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("客户端连接到服务器成功");
                    }else {
                        System.out.println("客户端连接到服务器失败");
                    }
                }
            });
            Channel channel = future.channel();
            System.out.println("-------" +
                    channel.localAddress().toString().substring(1) + "--------");
            Scanner scanner = new Scanner(System.in);

            while (true){
                String s = scanner.nextLine();
                if (s.equals("exit")){
                    break;
                }
                channel.writeAndFlush(s);
            }

            channel.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
